import { HttpParams } from '@angular/common/http';
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { _HttpClient, SettingsService } from '@delon/theme';
import format from 'date-fns/format';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-business-comment',
  templateUrl: './comment.component.html'
})
export class BusinessCommentComponent implements OnInit {
  url = `api/comments`;
  exportUrl = `api/comment/export`;
  isAdmin = false;
  isShow = false;
  company_id = 0;
  total = 0;
  pi = 1;
  ps = 30;
  loading = true;
  listOfData = [];
  q: {
    searchType: any;
    sn: string;
    shopId: number;
    companyId: number;
    keywordType: string;
    keywordVal: string;
    title: string;
    dimension: number;
    date: string;
  } = {
    sn: '',
    shopId: 0,
    companyId: 0,
    keywordType: 'itemId',
    keywordVal: '',
    title: '',
    dimension: -1,
    date: '',
    searchType: []
  };
  shops = [];
  shopMap = {};
  shopMapFull = {};
  companyMapFull = {};
  dimensionCount = {};
  stOptions = [
    { label: '带图', value: 0 },
    { label: '带文字', value: 1 },
    { label: '不展示默认好评', value: 2 }
  ];
  dimensionMap = {
    '1': '好评',
    '4': '好评',
    '2': '差评'
  };
  keywordType = [
    { label: '商品 ID', value: 'itemId' },
    { label: 'SKU ID', value: 'skuId' } /*,
    { label: '产品标题', value: 'title' }*/
  ];

  dateRange = [];
  searchType = [];

  constructor(
    private http: _HttpClient,
    private msgSrv: NzMessageService,
    private cdr: ChangeDetectorRef,
    private settingService: SettingsService
  ) {
    this.company_id = this.settingService.user.company_id;
    //console.log(this.settingService.user.ID);
    if (this.settingService.user.ID == 1) {
      this.isAdmin = true;
    }
    this.loadCompanies();
    this.loadShops();
  }

  loadShops(companyID: number = 0): void {
    this.http.get(`api/shop_map`, { companyId: companyID }).subscribe(res => {
      this.shops = res.data['shops'];
      for (let i = 0; i < this.shops.length; i++) {
        // @ts-ignore
        this.shopMap[this.shops[i]['shop_id']] = this.shops[i]['fordeal_shop_name'];
      }
    });
    this.http.get(`api/shop_map_full`, { companyId: companyID }).subscribe(res => {
      this.shops = res.data['shops'];
      for (let i = 0; i < this.shops.length; i++) {
        // @ts-ignore
        this.shopMapFull[this.shops[i]['shop_id']] = this.shops[i]['fordeal_shop_name'];
        this.companyMapFull[this.shops[i]['shop_id']] = this.shops[i]['company_name'];
      }
    });
  }

  ngOnInit(): void {
    this.loadDimensionCount();
    this.loadDataFromServer();
  }

  loadDimensionCount(): void {
    this.http.get(`api/comment/dimension_count`, this.q).subscribe(res => {
      this.dimensionCount = res.data;
    });
  }

  loadDataFromServer(): void {
    this.q.searchType = this.searchType.map(String).join(',');
    let params = new HttpParams().append('pi', this.pi).append('ps', this.ps).appendAll(this.q);
    this.http.get(`${this.url}`, params).subscribe(res => {
      if (res.err_code != 0) {
        this.msgSrv.error(res.msg);
        return;
      }
      this.total = res.data.total;
      this.listOfData = res.data.list;
      this.loading = false;
    });
  }

  pageIndexChange(pageIndex: number): void {
    this.loading = true;
    this.pi = pageIndex;
    this.loadDataFromServer();
  }

  pageSizeChange(pageSize: number): void {
    this.loading = true;
    this.ps = pageSize;
    this.loadDataFromServer();
  }

  search(): void {
    this.loading = true;
    this.pi = 1;
    this.ps = 30;
    this.loadDataFromServer();
    this.loadDimensionCount();
  }

  tabSelect(value: any): void {
    this.loading = true;
    this.q.dimension = value;
    this.pi = 1;
    this.ps = 30;
    this.loadDataFromServer();
  }

  commentedAtChange($event: any) {
    let s = format($event[0], 'yyyy-MM-dd');
    let e = format($event[1], 'yyyy-MM-dd');
    this.q.date = `${s}~${e}`;
  }

  exporting = false;
  export() {
    this.http.get(`api/comment/export`, this.q, { responseType: 'blob' }).subscribe(res => {
      this.exporting = true;
      if (res.type == 'application/json') {
        res.text().then((jsonResp: string) => {
          let js = JSON.parse(jsonResp);
          this.msgSrv.error(js.msg);
          this.exporting = false;
        });
        return;
      }
      let file = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      let fileURL = URL.createObjectURL(file);
      window.open(fileURL);
      this.exporting = false;
    });
  }

  companyList = [];
  loadCompanies(): void {
    this.http.get(`api/company_map`).subscribe(res => {
      this.companyList = res.data;
      if (this.companyList.length > 1) {
        this.isShow = true;
      }
    });
  }
  companyChange(companyID: number) {
    this.loadShops(companyID);
    this.cdr.detectChanges();
  }

  getTime(timestamp: string) {
    if (timestamp && timestamp != '') {
      var date = new Date(parseInt(timestamp) * 1000);
      let Y = date.getFullYear(),
        M = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1,
        D = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate(),
        h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours(),
        m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes(),
        s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
      timestamp = `${Y}-${M}-${D} ${h}:${m}:${s}`;
    }
    return timestamp;
  }
}
